<template>
	<view style="margin: 10px;background-color: #fff;border-radius: 10px;">
		<!-- <image class="logo" src="/static/logo.png"></image> -->
	    <view style="padding: 15px;padding-top: 15px;">
			<uni-forms ref="baseForm" :rules="rules" :modelValue="FormData">
				<uni-forms-item label="检查人:">
					<uni-easyinput v-model="FormData.userName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="部门:" v-if="!singleShop">
					<uni-easyinput v-model="FormData.deptName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="车间:" required name="workshopId">
					<!-- <uni-data-select
						v-if="!singleShop"
						v-model="FormData.workshopId"
						:localdata="shopOption"
						@change="selectChange"
						:clear="false"
					></uni-data-select> -->
					<uni-easyinput v-if="singleShop" v-model="FormData.workshop" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="整改条线:" required name="workshopareaId" v-if="FormData.lineId !=null">
					<uni-easyinput v-model="FormData.lineName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="区域:" required name="workshopareaId">
					<uni-easyinput v-if="singleShop" v-model="FormData.workshoparea" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="6源问题:" v-if="FormData.sixProblem !=''">
					<uni-easyinput v-if="singleShop" v-model="FormData.sixProblem" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="检查时间:" required name="createTime">
					<uni-easyinput v-if="singleShop" v-model="FormData.createTime" disabled="true"/>
					<!-- <uni-datetime-picker type="datetime" :clear-icon="false" v-model="FormData.createTime" @maskClick="maskClick" disabled/> -->
				</uni-forms-item>
				<uni-forms-item label="问题描述:" required name="description">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.description" placeholder="请输入问题"/>
					<!-- 推荐内容弹框 -->
					<!-- <uni-popup ref="descriptionsPopup" type="bottom">
					  <view class="recommendations-box">
					    <view
					      v-for="(item, index) in recommendationsDes"
					      :key="index"
					      class="recommendation-item"
					      @click="selectDescription(item)"
					    >
					      {{ item }}
					    </view>
						<view v-if="recommendationsDes.length === 0">无匹配结果</view>
					  </view>
					</uni-popup> -->
				</uni-forms-item>
				<uni-forms-item label="图片上传:" required name="frontImageListData">
					<uni-file-picker class="form-up-file" fileMediatype="image" :image-styles="imageStyles" ref="filePicker"  v-model="imageList"  limit="9" @progress="progress" @select='onFileChange' @delete='imgDelet'></uni-file-picker>
				</uni-forms-item>
			</uni-forms>
			<view>
					<button type="primary" class="uni-button-color" @click="clickInter('baseForm')">提交</button>
				</view>
		</view>
	</view>
</template>

<script>
	import { post, fileUpLoad, postForm } from '../../../utils/request.js';
	export default {
		data() {
			return {
				id: '',
				// 校验规则
				rules: {
					frontImageListData: {
						rules: [{
							required: true,
							errorMessage: '请上传图片'
						}]
					},
					workshopareaId: {
						rules: [{
							required: true,
							errorMessage: '请选择检查区域'
						}]
					},
					workshopId: {
						rules: [{
							required: true,
							errorMessage: '请选择车间'
						}]
					},
					description: {
						rules: [{
							required: true,
							errorMessage: '请输入问题描述'
						}]
					},
					createTime: {
						rules: [{
							required: true,
							errorMessage: '请选择检测时间'
						}]
					}
				},
				popupName: 'name',
				deptName: '',
				singleShop: true,
				imageList: [],
				imageStyles:{
					width:70,
					height:70,
					border:{
						color:"rgb(238, 238, 238)",
						width:2,
						style:'dashed',
						radius:'2px'
					}
				},
				title: '',
				userInfor: uni.getStorageSync('userInfor'),
				workshopName: '',
				userName: '',
				FormData: {
					checkUserId: '',
					createTime: Date.now(),
					description: '',
					frontImage: '',
					name: '',
					workshopId: '',
					workshopareaId: '',
					deptName: ''
				},
				recommendations: [], // 推荐内容列表
				recommendationsDes: [], // 推荐内容列表
				shopOption: [],
				spaceOption: [],
				single:  Date.now(),
				selectTab: 0,
				selected: {
					'点检问题': 0
				}
			}
		},
		onShow() {
			this.userInfor = uni.getStorageSync('userInfor')
			this.workshopName = this.userInfor.workshop
			this.workshopareaId = this.userInfor.workshopareaId
			//this.FormData.workshopId = this.userInfor.workshopId
			this.FormData.checkUserId = this.userInfor.userId
			//this.updataInfor()
		},
		onTabItemTap() {
			//debugger
			//this.clearData()
			//this.imgDelet()
		},
		onLoad(options) {
			this.id = options.id
			this.getData()
			//this.getInfor()
		},
		methods: {
			clearData() {
				this.FormData.createTime = Date.now()
				this.FormData.description = ''
				this.FormData.deptName = ''
				this.FormData.frontImage = ''
				this.FormData.name = ''
				this.FormData.workshopareaId = ''
				this.imageList = []
				this.$refs.filePicker.clearFiles();
			},
			// 处理输入事件
			nameInput() {
			    if (this.FormData.name) {
			      // 模拟推荐内容
			      this.recommendations = this.getNames(this.FormData.name);
			      this.$refs.namePopup.open(); // 打开弹框
			    } else {
			      this.recommendations = [];
			      this.$refs.namePopup.close(); // 关闭弹框
			    }
			},
			// 处理输入事件
			descriptionInput() {
			    if (this.FormData.description) {
			      // 模拟推荐内容
			      this.recommendationsDes = this.getDescriptions(this.FormData.description);
			      this.$refs.descriptionsPopup.open(); // 打开弹框
				  //debugger
			    } else {
			      this.recommendationsDes = [];
			      this.$refs.descriptionsPopup.close(); // 关闭弹框
			    }
			},
			  // 模拟获取推荐内容
			getNames(query) {
			    const allRecommendations = ['问题测试1', '测试2', '测试3', '测试4', '问题1', '问题2'];
			    return allRecommendations.filter(item => item.includes(query));
			},
			  // 模拟获取推荐内容
			getDescriptions(query) {
			    const allRecommendationsDes = ['描述1', '描述2', '描述3', '测试4', '问题1', '问题2'];
				//debugger
			    return allRecommendationsDes.filter(item => item.includes(query));
			},
			  // 选择推荐内容
			selectName(item) {
				this.FormData.name = item;
			    this.$refs.namePopup.close(); // 关闭弹框
			},
			  // 选择推荐内容
			selectDescription(item) {
				this.FormData.description = item;
			    this.$refs.descriptionsPopup.close(); // 关闭弹框
			},
			closepopName() {
				this.$refs.namePopup.close();
			},
			closepopDescrip() {
				this.$refs.descriptionsPopup.close(); 
			},
			clickInter(ref){
				let saveEdit = {
					description: this.FormData.description,
					frontImage: '',
					frontImageListData: this.FormData.frontImageListData,
					id: this.id,
					name: this.FormData.name
				}
				post('/problem/updateById', saveEdit)
				      .then(data => {
						  if(data.code == 200) {
							  uni.showToast({
							  	title: '数据修改成功！',
							  	duration: 1000
							  });
							uni.switchTab({
				                url: '/pages/work/index'
				            });
						  } else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						  }
				      })
				      .catch(err => {
				        uni.showToast({
				          icon: 'none',
				          title: '保存失败，请检查接口返回'
				        });
				      });
				/* this.FormData.checkUserId = this.userInfor.userId
						this.FormData.workshopId = this.userInfor.workshopId
						console.log(this.FormData, 'this.FormData')
						post('/problem/insert', this.FormData)
						      .then(data => {
								  if(data.code == 200) {
									  uni.showToast({
									  	title: '数据保存成功！',
									  	duration: 1000
									  });
									uni.switchTab({
						                url: '/pages/position/posAll/index'
						            });
									this.FormData.frontImage = ''
								  } else {
									  uni.showToast({
									    icon: 'none',
									    title: data.message
									  });
								  }
						      })
						      .catch(err => {
						        uni.showToast({
						          icon: 'none',
						          title: '保存失败，请检查接口返回'
						        });
						      }); */
				/* if(!this.FormData.frontImage) {
					uni.showToast({
						icon: 'none',
						title: '请检查上传图片！'
					});
					return;
				} else {
					if(!this.FormData.name || !this.FormData.description || !this.FormData.workshopareaId) {
						uni.showToast({
							icon: 'none',
							title: '请检查问题、区域、问题描述是否为空！'
						});
						return;
					} else {
						
					}
				} */
				
			},
			getData() {
				postForm('/problem/selectById', {id: this.id} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.FormData = data.data
							this.FormData.userName = this.userInfor.name
							this.FormData.deptName = this.userInfor.deptName
							let imgList = this.FormData.frontImageListData
							let img = []
							for (var i=0; i<imgList.length; i++) {
								img.push({
									url: imgList[i].url,
									extname: 'png',
									name: '图片.png'
								})
							}
							this.imageList = ''
							this.imageList = img
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			//获取用户车间、区域信息
			updataInfor() {
				let shop = this.userInfor.workshopList
				let area = this.userInfor.areaList
				let shopData = []
				let areaData = []
				for(var i = 0; i < shop.length; i++) {
					shopData[i] = {}
					shopData[i].value = shop[i].id
					shopData[i].text = shop[i].workshopName
				}
				this.shopOption = shopData
				if(this.shopOption.length > 1) {
					this.singleShop = false
				} else {
					this.singleShop = true
					this.FormData.workshopId = shopData[0].text
				}
				for(var i = 0; i < area.length; i++) {
					areaData[i] = {}
					areaData[i].value = area[i].id
					areaData[i].text = area[i].areaName
				}
				this.spaceOption = areaData
			},
			//车间、检车区域查询
			getInfor() {
				//车间
				post('/workshop/list')
				      .then(data => {
						  if(data.data!='fail') {
							  let opt = data.data
							  let midData =[]
							  for(var i = 0; i < opt.length; i++) {
								  midData[i] = {}
								  midData[i].value = opt[i].id
								  midData[i].text = opt[i].workshopName
							  }
						    this.shopOption = midData
						  } else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						  }
				      })
				      .catch(err => {
				        uni.showToast({
				          icon: 'none',
				          title: '查询失败，请检查接口返回'
				        });
				      });
				//区域
				post('/workshoparea/list')
				      .then(data => {
						  if(data.data!='fail') {
							  let opt = data.data
							  let midData =[]
							  for(var i = 0; i < opt.length; i++) {
								  midData[i] = {}
								  midData[i].value = opt[i].id
								  midData[i].text = opt[i].areaName
							  }
						    this.spaceOption = midData
						  } else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						  }
				      })
				      .catch(err => {
				        uni.showToast({
				          icon: 'none',
				          title: '查询失败，请检查接口返回'
				        });
				      });
			},
			progress() {
				console.log('sssss')
				//debugger
			},
			//文件上传
			async onFileChange(event) {
					try {
					    const files = event.tempFiles;
					    if (!files || files.length === 0) {
					      uni.showToast({ title: '请选择文件', icon: 'none', duration: 2000 });
					      return;
					    }
					
					    uni.showLoading({ title: '上传中...', mask: true });
					
					    // 循环上传，避免并发问题
					    for (const file of files) {
					      try {
					        let response = await fileUpLoad('/alone/uploadImages', file.path);
					        if (response) {
					          this.FormData.frontImageListData.push({ url: response });
					        }
					      } catch (error) {
					        console.error('单文件上传失败:', error);
					        // 可以继续上传其他文件，或 break 终止
					      }
					    }
					
					    uni.hideLoading();
					    uni.showToast({ title: '上传完成，等待提交！', icon: 'success', duration: 2000 });
					  } catch (error) {
					    uni.hideLoading();
					    uni.showToast({ title: '上传失败，请重试', icon: 'none', duration: 2000 });
					    console.error('文件上传错误:', error);
					  }
				
			},
			//图片删除
			imgDelet(e) {
				console.log(e)
				let index = e.index
				this.FormData.frontImageListData.splice(index, 1);
			},
			selectChange(e) {
				console.log(e)
			},
		    change(e) {
				this.FormData.createTime = e
				console.log('change事件:', this.single = e);
			},
			selChange() {},		
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			maskClick(e){
				console.log('maskClick事件:', e);
			}
		}
	}
</script>

<style>
	/* 模糊搜索弹框样式 */
	.recommendations-box {
	  background-color: #fff;
	box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
	  padding: 10px;
	  width: 80% !important;
	  max-height: 300px;
	  overflow-y: auto;
	  border-radius: 10px;
	}
	
	.recommendation-item {
		font-size: 15px;
	  /* padding: 10px;
	  border-bottom: 1px solid #eee; */
	}
	
	.recommendation-item:last-child {
	  border-bottom: none;
	}
	.uni-button-color {
		margin-top: 50px;
		background-color: #007aff !important;
	}
	/* .uni-forms-item {
	    margin-bottom: 16px !important;
	} */
	.is-disabled {
	    color: #000 !important;
	}
	/* uni-form  lable样式 */
	.uni-forms-item__label {
		font-weight: 600 !important;
		width: 80px !important;
	  text-align: right !important;
	  justify-content: flex-end !important;
	}
	.uni-stat__select {
	    display: flex;
	    align-items: center;
	    width: 100%;
	    flex: 1;
		height: 35px;
	    box-sizing: border-box;
		border: 1px solid #e5e5e5;
	}
	
</style>
